<?php
/**
 * Description
 *
 * PHP version 7
 *
 * @category Custom
 * @package  Custom
 * @author   ryu <mo5467@126.com>
 * @date     2020-04-23 00:41:20
 * @lastTime 2020-05-01 22:55:41
 * @license  https://opensource.org/licenses/MIT MIT License
 * @link     none
 */

namespace Design\Creational\Pool;

use Countable;

class WorkerPool implements Countable
{

    private $occupiedWorkers = [];

    private $freeWorkers = [];


    public function get(): StringReverseWorker
    {
        if (count($this->freeWorkers) === 0) {
            $worker = new StringReverseWorker();
        } else {
            $worker = array_pop($this->freeWorkers);
        }

        $this->occupiedWorkers[spl_object_hash($worker)] = $worker;

        return $worker;

    }//end get()


    public function dispose(StringReverseWorker $worker)
    {
        $key = spl_object_hash($worker);

        if (isset($this->occupiedWorkers[$key]) === true) {
            unset($this->occupiedWorkers[$key]);
            $this->freeWorkers[$key] = $worker;
        }

    }//end dispose()


    public function count()
    {
        return (count($this->freeWorkers) + count($this->occupiedWorkers));

    }//end count()


}//end class
